package com.nowcoder.community.util;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

@Component //交给IOC容器管理
public class MailClient {

    //需要添加日志，创建Logger日志对象
    public static final Logger logger = LoggerFactory.getLogger(MailClient.class);

    //委派第三方javaMailSender进行短信发送，javaMailSender发送邮件核心组件，由IOC容器统一管理，发送邮件核心组件
    @Autowired
    private JavaMailSender javaMailSender;

    //发送端固定，把username注入到bean容器中，而不需要每次都传进来
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发邮件方法
     */
    public void  sendMail(String to,String subject,String content) {
        try {
            //创建发送内容
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            //辅助生成内容组件
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage);
            //生产内容
            mimeMessageHelper.setFrom(from);
            mimeMessageHelper.setTo(to);
            mimeMessageHelper.setSubject(subject);
            mimeMessageHelper.setText(content,true);
            //发送
            javaMailSender.send(mimeMessageHelper.getMimeMessage());
        } catch (MessagingException e) {
           logger.error("发送邮件失效:"+e.getMessage());
        }

    }


}
